///////////////////////////////////////////////////////////////////////////////
// Name:        adacascadeclass.cpp
// Purpose:     Adacascadeclass function
// Copyright:   (c) 2006, Ivan Laptev, TT Solutions
// License:     GPL, Please contact us for commercial license.
//              http://www.tt-solutions.com/
///////////////////////////////////////////////////////////////////////////////
#include "objectdet/adacascadeclass.h"

#include "objectdet/adaclassmod.h"

/**
 * Try to figure out if the following region (rectangle) of the hist-image
 * represents the Goal.
 */
SubWindowInfo adacascadeclass(Model const & model,
                              arrMat integral_block_histogram,
                              size_t channels,
                              size_t left, size_t top,
                              size_t width, size_t height)
{
//%
//% [y,dfce]=adacascadeclass(X,cascademodel,ygrtruth,stnummax)
//%
//%  Classifies data X according to a AdaBoost cascade model.
//%  If the model is emplty, returns labels y=ones(1,size(X,2))
//%
//%  Inputs:
//%    X    [ndim,nsamples] input data
//%    
//%    cascademodel.stagemodel {model} one for each stage,
//%                            to be used with 'adaclassmod'
//%    cascademodel.fun='adacascadeclass' (optional)
//%
//%  Output:
//%    y    [1,nsamples] = 1: positive label / 2: negative label
//%    dfcecascade [2,nsamples] = 1st row: dfce
//%                               2nd row: stage

    assert( model.size() > 0 );

//    assert( stagenum < model.size() );
//
//    if (nargin < 3)
//        stagenum = cascademodel.stagemodels.size() - 1;

    double dfce = 0.;

    /**
     * Cycle through stages and if any particular stage fails then return false
     */
    Model::const_iterator model_it = model.begin();
    Model::const_iterator model_end = model.end();
    for(; model_it != model_end; ++model_it)
    {
        // check for every stage if the subwindow rect passes the stage test
        std::pair<bool,double> res = adaclassmod( *model_it,
                                                  integral_block_histogram,
                                                  channels,
                                                  left, top, width, height);
        dfce = res.second;
        if (!res.first)
            return SubWindowInfo(false, dfce, static_cast<size_t >(model_it - model.begin()),
                                 left, top, width, height);
    }
    // all stages passed -> return true
    // like in original algorithm we prefer (for a mysterious reason...) the dfce
    // obtained at the last stage
    return SubWindowInfo(true, dfce, static_cast<size_t >(model.size()),
                         left, top, width, height);
}
